package manager.socket;

import manager.config.SocketProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * springboot启动后，这里的socket也跟着自动加载启动
 * @author shidang.hu
 */
@Component
public class SocketRunner implements CommandLineRunner {

    @Autowired
    private SocketProperties properties;

    // 文件存储系统挂载的前置路径
    @Value("${sys.allocate.front.rootPath}")
    private String rootPath;

    @Value("${sys.file.encryption.flag}")
    private String encryptFlag;

    @Value("${sys.file.encryption.key}")
    private String encryptKey;

    @Override
    public void run(String... args) throws Exception {
        ServerSocket server = null;
        Socket socket = null;
        server = new ServerSocket(properties.getPort());
        System.out.println("设备服务器已经开启, 监听端口:" + properties.getPort());
        ThreadPoolExecutor pool = new ThreadPoolExecutor(
                properties.getPoolCore(),
                properties.getPoolMax(),
                properties.getPoolKeep(),
                TimeUnit.SECONDS,
                new ArrayBlockingQueue<Runnable>(properties.getPoolQueueInit()),
                new ThreadPoolExecutor.DiscardOldestPolicy()
        );
        while (true) {
            socket = server.accept();
            pool.execute(new HandlerFileProcessor(socket, rootPath, encryptFlag, encryptKey));
        }
    }
}
